package mysql

import (
	"gorm.io/gorm/clause"

	"mxshop_srvs/goods_srv/model"
	proto "mxshop_srvs/goods_srv/proto/gen/v1"
	mql "mxshop_srvs/shared/mysql"
)

func (g *Gorm) CategoryBrandExists(categoryID, brandID int32) (count int64, err error) {
	// result := g.db.Model(&model.GoodsCategoryBrand{}).Where(&model.GoodsCategoryBrand{
	// 	CategoryID: categoryID, BrandsID: brandID}).Count(&count).Limit(1)
	// return count, result.Error
	err = g.db.Raw("SELECT 1 FROM goods_category_brand WHERE category_id=? AND brands_id=? LIMIT 1",
		categoryID, brandID).Scan(&count).Error
	return count, err
}

func (g *Gorm) CategoryBrandByID(ID int32) (count int64, err error) {
	return count, g.db.Raw("SELECT 1 FROM goods_category_brand WHERE id=? LIMIT 1", ID).Scan(&count).Error
}

func (g *Gorm) CreateCategoryBrand(categoryID, brandId int32) (categoryBrand model.GoodsCategoryBrand, err error) {
	categoryBrand = model.GoodsCategoryBrand{
		BaseModel: model.BaseModel{
			ID:        mql.NewObjID,
			CreatedAt: mql.CreatedAt(),
		},
		CategoryID: categoryID,
		BrandsID:   brandId,
	}
	err = g.db.Create(&categoryBrand).Error
	return categoryBrand, err
}

func (g *Gorm) GetCategoryBrandCount() (count int64, err error) {
	return g.GetModelCount(&model.GoodsCategoryBrand{})
}

func (g *Gorm) CategoryBrandList(req *proto.CategoryBrandFilterRequest) (categoryBrands []model.GoodsCategoryBrand, err error) {
	return categoryBrands, g.db.Preload("Category").Preload(
		"Brands").Scopes(Paginate(int(req.Pages), int(req.PagePerNums))).Find(&categoryBrands).Error
}

func (g *Gorm) GetCategoryBrandList(categoryID int32) (categoryBrands []model.GoodsCategoryBrand, err error) {
	return categoryBrands, g.db.Preload("Category").Preload(
		"Brands").Where(&model.GoodsCategoryBrand{CategoryID: categoryID}).Find(&categoryBrands).Error
}

func (g *Gorm) UpdateCategoryBrand(req *proto.CategoryBrandRequest) (int64, model.GoodsCategoryBrand, error) {
	var categoryBrand = model.GoodsCategoryBrand{
		BaseModel:  model.BaseModel{ID: req.Id},
		CategoryID: req.CategoryId,
		BrandsID:   req.BrandId,
	}
	result := g.db.Clauses(clause.Returning{}).Updates(&categoryBrand)
	return result.RowsAffected, categoryBrand, result.Error
}

func (g *Gorm) DeleteCategoryBrand(ID int32) (int64, error) {
	result := g.db.Delete(&model.GoodsCategoryBrand{
		BaseModel: model.BaseModel{
			ID: ID,
		},
	})
	return result.RowsAffected, result.Error
}
